<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="用户名：">
        <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
        >
          搜索
        </el-button>
        <el-button size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser">
      添加用户
    </el-button>
    <el-button
      type="primary"
      size="default"
      :disabled="selectIdArr.length ? false : true"
      @click="deleteSelectUser"
    >
      批量删除
    </el-button>
    <el-table
      border
      style="margin: 10px 0px"
      :data="userArr"
      @selection-change="selectChange"
    >
      <el-table-column align="center" type="selection"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setRole(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            width="200"
            confirm-button-text="OK"
            cancel-button-text="No, Thanks"
            :icon="InfoFilled"
            icon-color="#626AEF"
            :title="`你确定要删除${row.username}吗?`"
            @confirm="delUser(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getHasUser"
    />
  </el-card>
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请输入姓名"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请输入昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请输入密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 用于某一个账号职位的分配 -->
  <el-drawer v-model="assignRoleDrawer">
    <template #header>
      <h4>用户角色用户</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.name" :disable="true"></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            Check all
          </el-checkbox>
          <el-checkbox-group
            v-model="checkedRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="role in roles"
              :key="role"
              :label="role"
              :value="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="assignRoleDrawer = false">取消</el-button>
        <el-button type="primary" @click="confirmRoleClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqAssignRole,
  reqDeleteUser,
  reqBatchDeleteUser,
} from '@/api/acl/user/index'
import type {
  UserResponseData,
  Records,
  User,
  AllRoleResponseData,
  AllRole,
  assignRolesData,
  RoleData,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
const pageNo = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(0)
const userArr = ref<Records>([])
const drawer = ref<boolean>(false)
const assignRoleDrawer = ref<boolean>(false)

// 获取模板setting仓库
const settingStore = useLayOutSettingStore()
const checkAll = ref(false)
const isIndeterminate = ref(true)
let checkedRoles = ref<AllRole>([])
const roles = ref<AllRole>([])
// 存储选中ID的数组
const selectIdArr = ref<User[]>([])
// 存储搜索关键字
const keyword = ref<string>('')
// 全选/全不选
const handleCheckAllChange = (val: boolean) => {
  checkedRoles.value = val ? roles.value : []
  isIndeterminate.value = false
}
// 子项选中收集
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length
}

const userParams = reactive<User>({
  username: '',
  password: '',
  name: '',
})
// 获取form组件实例
const formRef = ref<any>()
// 收集用的信息的响应式数据
onMounted(() => {
  getHasUser()
})

const getHasUser = async (page = 1) => {
  pageNo.value = page
  const result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}

const handleSizeChange = () => {
  getHasUser()
}

const addUser = () => {
  // 打开抽屉
  drawer.value = true
  // 清空输入框数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    password: '',
    name: '',
  })
  // 清除上一次错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}

const updateUser = (row: User) => {
  drawer.value = true
  Object.assign(userParams, row)
  // 清除上一次错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}
// 删除某一个用户
const delUser = async (userId: number) => {
  const result: any = await reqDeleteUser(userId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(pageSize.value > 1 ? pageNo.value : pageNo.value - 1)
  }
}

// 分配角色按钮回调
const setRole = async (row: User) => {
  Object.assign(userParams, row)
  const result: AllRoleResponseData = await reqAllRole(row.id as number)
  if (result.code == 200) {
    // 存储数据
    roles.value = result.data.allRolesList
    checkedRoles.value = result.data.assignRoles
    // 显示抽屉
    assignRoleDrawer.value = true
  }
}

// 确认按钮回调；可以保存可以更新
const confirmClick = async () => {
  // 点击保存：务必确保全部校验通过发请求
  await formRef.value.validate()
  // 保存按钮：添加新的用户|更新已有的用户账号信息
  const result: any = await reqAddOrUpdateUser(userParams)
  if (result.code == 200) {
    // 关闭抽屉
    drawer.value = false
    // 提示消息
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    // 获取最新的全部账号信息
    // 无论是添加还是更新浏览器刷新会自动回到第一页；所以下面一行的代码可以注释了
    // getHasUser(userParams.id ? pageNo.value : 1)
    // 修改自己的账户信息，需要刷新浏览器；账户自动退出
    // 浏览器自动刷新一次
    window.location.reload()
  } else {
    // 关闭抽屉
    drawer.value = false
    // 提示消息
    ElMessage({
      type: 'error',
      message: '更新失败',
    })
  }
}
// 取消按钮回调
const cancelClick = () => {
  drawer.value = false
}
// 分配职位确定按钮回调
const confirmRoleClick = async () => {
  const data: assignRolesData = {
    // 收集角色信息列表
    roleIdList: checkedRoles.value.map((item: RoleData) => item.id as number),
    // 收集用户id
    userId: userParams.id as number,
  }
  // 发请求
  const result: any = await reqAssignRole(data)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配角色成功',
    })
    // 关闭抽屉
    assignRoleDrawer.value = false
    // 请求最新数据;留在当前页
    getHasUser(pageNo.value)
  }
}
const checkUsername = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('Please input the username'))
  }
  setTimeout(() => {
    if (value.trim().length >= 5) {
      callback()
    } else {
      callback(new Error('用户名字至少五位'))
    }
  }, 1000)
}

const checkName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('Please input the name'))
  }
  setTimeout(() => {
    if (value.trim().length >= 5) {
      callback()
    } else {
      callback(new Error('用户名字至少五位'))
    }
  }, 1000)
}

const checkPassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('Please input the password'))
  }
  setTimeout(() => {
    if (value.trim().length >= 6) {
      callback()
    } else {
      callback(new Error('用户名字至少六位'))
    }
  }, 1000)
}
// 表单校验的规则对象
const rules = {
  username: [{ require: true, trigger: 'blur', validator: checkUsername }],
  name: [{ require: true, trigger: 'blur', validator: checkName }],
  password: [{ require: true, trigger: 'blur', validator: checkPassword }],
}
const selectChange = (value: any) => {
  selectIdArr.value = value
}
// 批量删除按钮的回调
const deleteSelectUser = async () => {
  // 整理参数
  const idList: any = selectIdArr.value.map((item: User) => {
    return item.id
  })
  // 发送请求
  const result: any = await reqBatchDeleteUser(idList)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(
      pageSize.value > selectIdArr.value.length
        ? pageNo.value
        : pageNo.value - 1,
    )
  }
}
// 搜索
const search = () => {
  getHasUser()
  keyword.value = ''
}
// 重置
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
